package com.lhd.qd.module.system.dict.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lhd.qd.common.base.BasePageQuery;
import com.lhd.qd.common.base.BaseServiceImpl;
import com.lhd.qd.common.exception.BusinessException;
import com.lhd.qd.module.system.dict.dao.DictTypeMapper;
import com.lhd.qd.module.system.dict.model.dataobj.DictTypeDO;
import com.lhd.qd.module.system.dict.model.dto.DictTypeSaveDTO;
import com.lhd.qd.module.system.dict.model.dto.DictTypeUpdateDTO;
import com.lhd.qd.module.system.dict.model.vo.DictTypeDetailVO;
import com.lhd.qd.module.system.dict.model.vo.DictTypeListVO;
import com.lhd.qd.module.system.dict.service.DictTypeService;
import com.lhd.qd.module.system.dict.model.converter.AbstractDictTypeConverter;
import com.lhd.qd.module.system.dict.service.DictCacheService;
import com.lhd.qd.module.system.dict.service.DictService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class DictTypeServiceImpl extends BaseServiceImpl<DictTypeMapper, DictTypeDO> implements DictTypeService {

    @Autowired
    private DictService dictService;

    @Autowired
    private DictCacheService dictCacheService;

    @Override
    public IPage<DictTypeListVO> pageDictType(BasePageQuery query) {

        LambdaQueryWrapper<DictTypeDO> queryWrapper = Wrappers.<DictTypeDO>lambdaQuery();

        IPage<DictTypeDO> doPage = page(new Page<>(query.getCurrent(), query.getSize()), queryWrapper);

        return AbstractDictTypeConverter.INSTANCE.doPage2ListVOPage(doPage);
    }

    @Override
    public DictTypeDetailVO getDictTypeById(String code) {

        return AbstractDictTypeConverter.INSTANCE.do2DetailVO(getById(code));
    }

    @Override
    public boolean saveDictType(DictTypeSaveDTO saveDTO) {

        int count = count(Wrappers.<DictTypeDO>lambdaQuery().eq(DictTypeDO::getCode, saveDTO.getCode()));
        if (count > 0) {
            throw new BusinessException("字典类型编码已存在，请更换。");
        }

        DictTypeDO dataObj = AbstractDictTypeConverter.INSTANCE.saveDTO2DO(saveDTO);

        return save(dataObj);
    }

    @Override
    public boolean updateDictTypeById(String code, DictTypeUpdateDTO updateDTO) {

        DictTypeDO dataObj = AbstractDictTypeConverter.INSTANCE.updateDTO2DO(updateDTO);

        dataObj.setCode(code);

        return updateById(dataObj);
    }

    @Override
    public boolean removeDictTypeById(String code) {

        dictService.removeDictByTypeCode(code);

        boolean isSuccess = removeById(code);

        dictCacheService.refreshCache(code);

        return isSuccess;
    }
}
